package comgame.scenes;

import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Label;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BoxPane extends VBox {
    private TableView<Item> tableView;
    private static final int MAX_ITEM_SLOTS = 20;

    public BoxPane() {
        setVisible(false);
        setStyle("-fx-background-color: rgba(255,255,255,0.92); -fx-background-radius: 12; -fx-padding: 10; -fx-border-radius: 12; -fx-border-color: #888;");
        setMaxWidth(350);
        setMaxHeight(340);
        setSpacing(8);
        setAlignment(Pos.CENTER);

        Label title = new Label("物品箱");
        title.setStyle("-fx-font-size: 28px; -fx-font-weight: bold; -fx-text-fill: #333;");
        title.setPadding(new Insets(0,0,5,0));

        tableView = new TableView<>();
        tableView.setPrefHeight(400);
        tableView.setPrefWidth(350);
        tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
        tableView.setStyle("-fx-font-size: 14px;");

        // 图片列
        TableColumn<Item, String> imageCol = new TableColumn<>("图片");
        imageCol.setCellValueFactory(new PropertyValueFactory<>("imagePath"));
        imageCol.setPrefWidth(40);
        imageCol.setCellFactory(col -> new TableCell<Item, String>() {
            private final ImageView imageView = new ImageView();
            @Override
            protected void updateItem(String imagePath, boolean empty) {
                super.updateItem(imagePath, empty);
                if (empty || imagePath == null || imagePath.isEmpty()) {
                    setGraphic(null);
                } else {
                    try {
                        Image img = new Image(getClass().getResourceAsStream(imagePath), 30, 30, true, true);
                        imageView.setImage(img);
                        setGraphic(imageView);
                    } catch (Exception e) {
                        setGraphic(null);
                    }
                }
            }
        });

        // 名称列
        TableColumn<Item, String> nameCol = new TableColumn<>("物品名称");
        nameCol.setCellValueFactory(new PropertyValueFactory<>("name"));
        nameCol.setPrefWidth(120);
        nameCol.setStyle("-fx-font-size: 14px;");
        // 空栏位不显示名称
        nameCol.setCellFactory(col -> new TableCell<Item, String>() {
            @Override
            protected void updateItem(String name, boolean empty) {
                super.updateItem(name, empty);
                if (empty || name == null || name.isEmpty()) {
                    setText("");
                } else {
                    setText(name);
                }
            }
        });

        // 数量列
        TableColumn<Item, Integer> countCol = new TableColumn<>("数量");
        countCol.setCellValueFactory(new PropertyValueFactory<>("count"));
        countCol.setPrefWidth(60);
        countCol.setStyle("-fx-font-size: 14px;");
        // 空栏位不显示数量
        countCol.setCellFactory(col -> new TableCell<Item, Integer>() {
            @Override
            protected void updateItem(Integer count, boolean empty) {
                super.updateItem(count, empty);
                if (empty || count == null || count == 0) {
                    setText("");
                } else {
                    setText(String.valueOf(count));
                }
            }
        });

        tableView.getColumns().addAll(imageCol, nameCol, countCol);

        getChildren().addAll(title, tableView);
    }

    // 刷新物品栏内容
    public void refreshItems() {
        // 使用Platform.runLater确保在JavaFX线程中执行
        javafx.application.Platform.runLater(() -> {
            try {
                tableView.getItems().clear();
                List<Item> items = new ArrayList<>();
                Map<String, Integer> itemData = ItemManager.getInstance().getAllItems();
                Map<String, String> itemImages = new HashMap<>();
                // 基础农作物
                itemImages.put("小麦", "/assets/textures/Fruit_Wheat.png");
                itemImages.put("番茄", "/assets/textures/Fruit_Tomato.png");
                itemImages.put("土豆", "/assets/textures/Fruit_Potato.png");
                itemImages.put("星果", "/assets/textures/Fruit_Starfruit.png");
                itemImages.put("胡萝卜", "/assets/textures/Fruit_Carrot.png");
                // 特殊农作物
                itemImages.put("南瓜", "/assets/textures/Fruit_Pumpkin.png");
                itemImages.put("霜瓜", "/assets/textures/Fruit_Powdermelon.png");
                itemImages.put("幽灵辣椒", "/assets/textures/Fruit_GhostPaper.png");
                itemImages.put("水龙果", "/assets/textures/Fruit_WaterDragon.png");
                itemImages.put("齐瓜", "/assets/textures/Fruit_Qi_Fruit.png");
                // 显示所有农作物
                String[] crops = {"小麦", "番茄", "土豆", "星果", "胡萝卜", "南瓜", "霜瓜", "幽灵辣椒", "水龙果", "齐瓜"};
                for (String crop : crops) {
                    Integer count = itemData.get(crop);
                    if (count != null && count > 0) {
                        String imagePath = itemImages.getOrDefault(crop, "");
                        items.add(new Item(crop, count, imagePath));
                    }
                }
                // 补充空栏位（总共显示10个栏位）
                int minSlots = 10;
                while (items.size() < minSlots) {
                    items.add(new Item("", 0, ""));
                }
                tableView.getItems().addAll(items);
                
                // 强制刷新TableView
                tableView.refresh();
                
                // 调试信息
                System.out.println("BoxPane刷新完成，当前物品数量: " + itemData.size());
                for (String crop : crops) {
                    Integer count = itemData.get(crop);
                    if (count != null && count > 0) {
                        System.out.println("  " + crop + ": " + count);
                    }
                }
            } catch (Exception e) {
                System.err.println("BoxPane刷新失败: " + e.getMessage());
                e.printStackTrace();
            }
        });
    }

    // 物品数据类
    public static class Item {
        private final javafx.beans.property.SimpleStringProperty name;
        private final javafx.beans.property.SimpleIntegerProperty count;
        private final javafx.beans.property.SimpleStringProperty imagePath;

        public Item(String name, int count, String imagePath) {
            this.name = new javafx.beans.property.SimpleStringProperty(name);
            this.count = new javafx.beans.property.SimpleIntegerProperty(count);
            this.imagePath = new javafx.beans.property.SimpleStringProperty(imagePath);
        }
        public String getName() { return name.get(); }
        public void setName(String n) { name.set(n); }
        public int getCount() { return count.get(); }
        public void setCount(int c) { count.set(c); }
        public String getImagePath() { return imagePath.get(); }
        public void setImagePath(String p) { imagePath.set(p); }
    }
} 